<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="文档名称" prop="materialName">
        <ns-input
          v-model="queryParams.materialName"
          class="!w-240px"
          clearable
          placeholder="请输入文档名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文档类型" prop="materialTypeValue">
        <ns-input
          v-model="queryParams.materialTypeValue"
          class="!w-240px"
          clearable
          placeholder="请输入文档类型"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文档描述" prop="materialDesc">
        <ns-input
          v-model="queryParams.materialDesc"
          class="!w-240px"
          clearable
          placeholder="请输入文档描述"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="添加日期" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-row>
        <el-col :span="24" class="text-right">
          <el-form-item>
            <el-button
              @click="handleQuery"
              type="primary"
              v-hasPermi="['amp:operation-message:search']"
            >
              搜索
            </el-button>
            <el-button @click="resetQuery" v-hasPermi="['amp:operation-message:search']">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div class="handle-btns">
      <el-button type="primary" @click="openForm" v-hasPermi="['amp:operation-message:upload']"
        >新增</el-button
      >
      <!-- <el-button>下载</el-button> -->
      <el-button
        type="danger"
        plain
        @click="handleDelete()"
        v-hasPermi="['amp:operation-message:delete']"
        >删除</el-button
      >
    </div>
    <el-table v-loading="loading" :data="list" ref="tableRef">
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="文档名称"
        align="center"
        prop="materialName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="文档类型"
        align="center"
        prop="materialTypeValue"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="文档描述"
        align="center"
        prop="materialDesc"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="添加日期"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            @click="handleDownload(scope.row)"
            link
            type="primary"
            v-hasPermi="['amp:operation-message:download']"
          >
            下载
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete([scope.row.id])"
            v-hasPermi="['amp:operation-message:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.page"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MaterialForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import MaterialForm from './EditForm.vue'
import { dateFormatter } from '@/utils/formatTime'
import { ElTable } from 'element-plus'
import { getMaterialPage, deleteMaterial } from '@/api/material/material'
import { fileExchange } from '@/api/infra/file'

defineOptions({ name: 'OperationManagement' })

const tableRef = ref<InstanceType<typeof ElTable>>()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const queryFormRef = ref() // 搜索的表单
const total = ref(0) // 列表的总页数
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  type: 2,
  materialName: '',
  materialDesc: '',
  materialTypeValue: '',
  createTime: []
})

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 激活时重置搜索 */
onActivated(() => {
  resetQuery()
})

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof MaterialForm>>()
const openForm = () => {
  formRef.value?.open('create')
}

// 下载文件
const handleDownload = async (row) => {
  const fileUrl = row.filePath
  const fileName = row.materialName + getFileExtension(fileUrl)
  // 获取文件下载地址
  const data = await fileExchange(fileUrl)
  fetch(data)
    .then((response) => {
      if (!response.ok) {
        throw new Error('下载失败')
      }
      return response.blob()
    })
    .then((blob) => {
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      window.URL.revokeObjectURL(url)
    })
    .catch((error) => {
      console.error('下载失败:', error)
    })
}
// 辅助函数：获取文件扩展名
const getFileExtension = (url) => {
  const lastDotIndex = url.lastIndexOf('.')
  return lastDotIndex === -1 ? '' : url.substring(lastDotIndex)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const { count, data } = await getMaterialPage(toRaw(queryParams))
    list.value = data
    total.value = count
  } finally {
    loading.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = async (ids?: number[]) => {
  try {
    const ids_ = ids ? ids : (tableRef.value?.getSelectionRows().map((item) => item.id) as number[])
    if (ids_ && ids_.length === 0) {
      await message.confirm('请选择需要删除的项')
      return
    }
    // 删除的二次确认
    await message.delConfirm()

    // 发起删除
    await deleteMaterial(ids_)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.handle-btns {
  margin-bottom: 20px;
}
</style>
